﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Neoit.Utils.Security
{
    /// <summary>
    /// 非对称加密RSA
    /// </summary>
    public class RsaHelper
    {
        private readonly HashAlgorithmName _hashAlgorithmName;
        private readonly Encoding _encoding;
        private bool _canInstantiatedRSA;

        #region 实例化RSAHelper
        /// <summary>
        /// 实例化RSAHelper
        /// </summary>
        /// <param name="hashAlgorithmName">算法名称</param>
        /// <param name="encoding">编码方式</param>
        /// <param name="privateKey"></param>
        /// <param name="publicKey"></param>
        public RsaHelper(HashAlgorithmName hashAlgorithmName, Encoding encoding = null, string privateKey = null, string publicKey = null)
        {
            _encoding = encoding ?? Encoding.UTF8;
            _hashAlgorithmName = hashAlgorithmName;

            using RSA rsa = RSA.Create();

            if (!string.IsNullOrEmpty(privateKey))
            {
                _canInstantiatedRSA = ParseBase64(FormatKey(privateKey), out byte[] bytes);
                if (!_canInstantiatedRSA) return;

                SetPrivateKey(rsa, bytes);
            }

            if (!string.IsNullOrEmpty(publicKey))
            {
                _canInstantiatedRSA = ParseBase64(FormatKey(publicKey), out byte[] bytes);
                if (!_canInstantiatedRSA) return;
                SetPublicKey(rsa, bytes);
            }
        }
        #endregion

        #region 加密/解密

        #endregion

        #region 签名/验签
        /// <summary>
        /// 验签
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="data"></param>
        /// <param name="sign"></param>
        /// <param name="hashAlgorithmName"></param>
        /// <returns></returns>
        public static bool VerifySign(string publicKey, string data, string sign, HashAlgorithmName hashAlgorithmName)
        {
            if (ParseBase64(FormatKey(publicKey), out byte[] bytes))
            {
                using RSA rsa = RSA.Create();
                SetPublicKey(rsa, bytes);

                byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                if (!ParseBase64(sign, out byte[] signBytes)) return false;
                return rsa.VerifyData(dataBytes, signBytes, hashAlgorithmName, RSASignaturePadding.Pkcs1);
            }
            return false;
        }
        #endregion

        #region 生成公私钥
        public static (string publicKey, string privateKey) CreateRSAKey(int keySizeInBits = 1024)
        {
            using RSA rsa = RSA.Create(keySizeInBits);
            return (Convert.ToBase64String(rsa.ExportRSAPublicKey()), Convert.ToBase64String(rsa.ExportRSAPrivateKey()));
        }
        public static (string publicKey, string privateKey) CreateRSAKeyPEM(int keySizeInBits = 1024)
        {
            var key = CreateRSAKey(keySizeInBits);
            var publicKeyPEM = $"-----BEGIN PUBLIC KEY-----\n" + ConvertToPEM(key.publicKey) + "\n-----END PUBLIC KEY-----";
            var privateKeyPEM = $"-----BEGIN RSA PRIVATE KEY-----\n" + ConvertToPEM(key.privateKey) + "\n-----END RSA PRIVATE KEY-----";
            return (publicKeyPEM, privateKeyPEM);
        }
        #endregion

        #region 工具方法
        static string ConvertToPEM(string input)
        {
            var splitLength = 64;
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < input.Length; i += splitLength)
            {
                int length = Math.Min(splitLength, input.Length - i);
                string substring = input.Substring(i, length);
                sb.Append(substring);

                if (i + splitLength < input.Length)
                {
                    sb.Append("\n");
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// 解析base64
        /// </summary>
        public static bool ParseBase64(string val, out byte[] res)
        {
            try
            {
                res = Convert.FromBase64String(val);
                return true;
            }
            catch
            {
                res = null;
                return false;
            }
        }
        #region 设置私钥

        void SetPrivateKey(RSA rsa, byte[] bytes)
        {
            var rsaParameters = new RSAParameters();
            using (BinaryReader binr = new BinaryReader(new MemoryStream(bytes)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                    binr.ReadByte();
                else if (twobytes == 0x8230)
                    binr.ReadInt16();
                else
                    throw new Exception("Unexpected value read binr.ReadUInt16()");

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                    throw new Exception("Unexpected version");

                bt = binr.ReadByte();
                if (bt != 0x00)
                    throw new Exception("Unexpected value read binr.ReadByte()");

                rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
                rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }

            rsa.ImportParameters(rsaParameters);
        }

        #endregion

        #region 设置公钥
        static void SetPublicKey(RSA rsa, byte[] bytes)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq = new byte[15];

            var x509Key = bytes;
            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            using (MemoryStream mem = new MemoryStream(x509Key))
            {
                using (BinaryReader binr = new BinaryReader(mem))  //wrap Memory Stream with BinaryReader for easy reading
                {
                    byte bt = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return;

                    seq = binr.ReadBytes(15);       //read the Sequence OID
                    if (!CompareBytearrays(seq, seqOid))    //make sure Sequence for OID is correct
                        return;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8203)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return;

                    bt = binr.ReadByte();
                    if (bt != 0x00)     //expect null byte next
                        return;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return;

                    twobytes = binr.ReadUInt16();
                    byte lowbyte = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                        lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte(); //advance 2 bytes
                        lowbyte = binr.ReadByte();
                    }
                    else
                        return;
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                    int modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {   //if first byte (highest order) of modulus is zero, don't include it
                        binr.ReadByte();    //skip this null byte
                        modsize -= 1;   //reduce modulus buffer size by 1
                    }

                    byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes

                    if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
                        return;
                    int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
                    byte[] exponent = binr.ReadBytes(expbytes);

                    // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                    RSAParameters rsaKeyInfo = new RSAParameters
                    {
                        Modulus = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);
                }
            }
        }

        #endregion

        #region 导入密钥算法

        int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else
            if (bt == 0x82)
            {
                var highbyte = binr.ReadByte();
                var lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;
            }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

        static bool CompareBytearrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
                return false;
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }
            return true;
        }

        #endregion

        #region 格式化公私钥字符串
        static string FormatKey(string content)
        {
            return content.Replace("-----BEGIN PUBLIC KEY-----", "")
                               .Replace("-----END PUBLIC KEY-----", "")
                               .Replace("-----BEGIN RSA PRIVATE KEY-----", "")
                               .Replace("-----END RSA PRIVATE KEY-----", "")
                               .Replace("\n", "");
        }
        #endregion
        #endregion
    }
}
